<?php
/**
*
* @package acp
* @version $Id: acp_express_articles.php,v 1.011 2008/03/09 17:32:00 nedka Exp $
* @copyright (c) 2008 nedka (Nguyen Dang Khoa)
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/

/**
* @ignore
*/
if (!defined('IN_PHPBB'))
{
	exit;
}

/**
* @package acp
*/
class acp_express_articles
{
	var $u_action;

	function main($id, $mode)
	{
		global $db, $user, $template;
		global $config, $phpbb_root_path, $phpbb_admin_path, $phpEx;

		$user->add_lang('mods/express');

		// Set up general vars
		$action = request_var('action', '');
		$action = (isset($_POST['add'])) ? 'add' : $action;
		$action = (isset($_POST['save'])) ? 'save' : $action;
		$article_id = request_var('id', 0);
		$cat = request_var('cat', 0);
		$start = request_var('start', 0);

		// Sort keys
		$sort_days = request_var('st', 0);
		$sort_key = request_var('sk', 'd');
		$sort_dir = request_var('sd', 'a');

		$this->tpl_name = 'acp_express_articles';
		$this->page_title = 'ACP_EXPRESS_ARTICLES';

		$form_name = 'acp_express_articles';
		add_form_key($form_name);

		switch ($action)
		{
			case 'save':

				if (!check_form_key($form_name))
				{
					trigger_error($user->lang['FORM_INVALID']. adm_back_link($this->u_action), E_USER_WARNING);
				}

				$article_title = utf8_normalize_nfc(request_var('article_title', '', true));
				$article_cat = request_var('article_cat', 0);
				$article_intro = utf8_normalize_nfc(request_var('article_intro', '', true));
				$article_content = utf8_normalize_nfc(request_var('article_content', '', true));
				$article_image = request_var('article_image', '');
				$article_similar = request_var('article_similar', '');
				$article_source = request_var('article_source', '');

				// The article image has to be a jpg, gif or png
				if ($article_image != '' && !preg_match('#(\.gif|\.png|\.jpg|\.jpeg)$#i', $article_image))
				{
					$article_image = '';
				}

				if (!$article_title || !$article_cat)
				{
					trigger_error($user->lang['NO_ARTICLE_TITLE'] . adm_back_link($this->u_action), E_USER_WARNING);
				}

				$sql_ary = array(
					'article_title'				=> $article_title,
					'article_cat'				=> $article_cat,
					'article_intro'				=> $article_intro,
					'article_content'			=> $article_content,
					'article_content_uid'		=> '',
					'article_content_options'	=> 7,
					'article_content_bitfield'	=> '',
					'article_image'				=> htmlspecialchars_decode($article_image),
					'article_similar'			=> $article_similar,
					'article_source'			=> $article_source,
					'article_time'				=> time(),
				);

				// Get data for article content if specified
				if ($sql_ary['article_content'])
				{
					generate_text_for_storage($sql_ary['article_content'], $sql_ary['article_content_uid'], $sql_ary['article_content_bitfield'], $sql_ary['article_content_options'], request_var('parse_bbcode', false), request_var('parse_urls', false), request_var('parse_smilies', false));
				}

				if ($article_id)
				{
					$sql = 'SELECT article_cat
						FROM ' . EXPRESS_ARTICLES_TABLE . "
						WHERE article_id = $article_id";
					$result = $db->sql_query($sql);
					$old_cat = (int) $db->sql_fetchfield('article_cat');
					$db->sql_freeresult($result);

					// Update number of articles in old category and new category if need when we change category
					if ($old_cat != $article_cat)
					{
						// New category: +1
						$sql = 'UPDATE ' . EXPRESS_CATEGORIES_TABLE . " SET cat_articles = cat_articles + 1 WHERE cat_id = $article_cat";
						$db->sql_query($sql);						

						// Old category: -1
						$sql = 'UPDATE ' . EXPRESS_CATEGORIES_TABLE . " SET cat_articles = cat_articles - 1 WHERE cat_id = $old_cat";
						$db->sql_query($sql);						
					}

					$sql = 'UPDATE ' . EXPRESS_ARTICLES_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $sql_ary) . " WHERE article_id = $article_id";
					$db->sql_query($sql);

					$message = $user->lang['ARTICLE_UPDATED'];

					add_log('admin', 'LOG_EXPRESS_ARTICLE_UPDATED', $article_title);
				}
				else
				{
					$sql = 'INSERT INTO ' . EXPRESS_ARTICLES_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
					$db->sql_query($sql);

					$message = $user->lang['ARTICLE_ADDED'];

					// Update articles counter for selected category
					$sql = 'UPDATE ' . EXPRESS_CATEGORIES_TABLE . " SET cat_articles = cat_articles + 1 WHERE cat_id = $article_cat"; 
					$db->sql_query($sql);

					set_config('num_express_articles', $config['num_express_articles'] + 1, true);
					add_log('admin', 'LOG_EXPRESS_ARTICLE_ADDED', $article_title);
				}

				set_config('express_last_updated', time(), true);
				trigger_error($message . adm_back_link($this->u_action));

			break;

			case 'delete':

				if (!$article_id)
				{
					trigger_error($user->lang['MUST_SELECT_ARTICLE'] . adm_back_link($this->u_action), E_USER_WARNING);
				}

				if (confirm_box(true))
				{
					$sql = 'SELECT article_id, article_title
						FROM ' . EXPRESS_ARTICLES_TABLE . "
						WHERE article_id = $article_id";
					$result = $db->sql_query($sql);
					$row = $db->sql_fetchrow($result);
					$db->sql_freeresult($result);

					if ($row)
					{
						$row['article_title'] = (string) $row['article_title'];
						$row['article_cat'] = (int) $row['article_cat'];
					}

					// Delete this article
					$sql = 'DELETE FROM ' . EXPRESS_ARTICLES_TABLE . " WHERE article_id = $article_id";
					$db->sql_query($sql);

					// Delete all rates for this article
					$sql = 'DELETE FROM ' . EXPRESS_RATES_TABLE . " WHERE article_id = $article_id";
					$db->sql_query($sql);

					// Delete all comments about this article
					$sql = 'DELETE FROM ' . EXPRESS_COMMENTS_TABLE . " WHERE article_id = $article_id";
					$db->sql_query($sql);

					// Update articles counter for selected category
					$sql = 'UPDATE ' . EXPRESS_CATEGORIES_TABLE . ' SET cat_articles = cat_articles - 1 WHERE cat_id = ' . $row['article_cat']; 
					$db->sql_query($sql);

					set_config('num_express_articles', $config['num_express_articles'] - 1, true);
					add_log('admin', 'LOG_EXPRESS_ARTICLE_REMOVED', $row['article_title']);
				}
				else
				{
					confirm_box(false, $user->lang['CONFIRM_OPERATION'], build_hidden_fields(array(
						'i'				=> $id,
						'mode'			=> $mode,
						'article_id'	=> $article_id,
						'action'		=> 'delete',
					)));
				}

			break;

			case 'edit':
			case 'add':

				include_once($phpbb_root_path . 'includes/functions_display.' . $phpEx);

				$user->add_lang('posting');

				// Assigning custom bbcodes
				display_custom_bbcodes();

				$articles = $existing_imgs = array();

				$sql = 'SELECT *
					FROM ' . EXPRESS_ARTICLES_TABLE . '
					ORDER BY article_title';
				$result = $db->sql_query($sql);

				while ($row = $db->sql_fetchrow($result))
				{
					$existing_imgs[] = $row['article_image'];

					if ($action == 'edit' && $article_id == $row['article_id'])
					{
						$articles = $row;
					}
				}
				$db->sql_freeresult($result);

				$img_list = filelist($phpbb_root_path . $config['express_article_images_path'], '');
				$edit_img = $img_filename_list = '';

				foreach ($img_list as $path => $img_ary)
				{
					sort($img_ary);

					foreach ($img_ary as $img)
					{
						$img = $path . $img;

						if (!in_array($img, $existing_imgs) || $action == 'edit')
						{
							if ($articles && $img == $articles['article_image'])
							{
								$selected = ' selected="selected"';
								$edit_img = $img;
							}
							else
							{
								$selected = '';
							}

							if (strlen($img) > 255)
							{
								continue;
							}

							$img_filename_list .= '<option value="' . htmlspecialchars($img) . '"' . $selected . '>' . $img . '</option>';
						}
					}
				}

				$img_filename_list = '<option value=""' . (($edit_img == '') ? ' selected="selected"' : '') . '>' . $user->lang['SELECT_ARTICLE_IMAGE'] . '</option>' . $img_filename_list;
				unset($existing_imgs, $img_list);

				// Select category for articles
				$sql = 'SELECT cat_id, cat_name
					FROM ' . EXPRESS_CATEGORIES_TABLE . '
					ORDER BY cat_name';
				$result = $db->sql_query($sql);

				$s_cat_options = '<option value="0"' . ((!isset($articles['article_cat'])) ? ' selected="selected"' : '') . '>' . $user->lang['SELECT_ARTICLE_CAT'] . '</option>';

				while ($row = $db->sql_fetchrow($result))
				{
					$selected = (isset($articles['article_cat']) && $row['cat_id'] == $articles['article_cat']) ? ' selected="selected"' : '';
					$s_cat_options .= '<option value="' . $row['cat_id'] . '"' . $selected . '>' . $row['cat_name'] . '</option>';

					if ($selected)
					{
						// Update artcle's category
						$sql = 'UPDATE ' . EXPRESS_ARTICLES_TABLE . '
							SET article_cat = ' . $articles['article_cat'] . '
							WHERE article_id = ' . $article_id;
						$db->sql_query($sql);
					}
				}
				$db->sql_freeresult($result);

				// Article content with BBCode support
				$article_content_data = array(
					'text'			=> (isset($articles['article_content'])) ? $articles['article_content'] : '',
					'allow_bbcode'	=> true,
					'allow_smilies'	=> true,
					'allow_urls'	=> true
				);

				$article_content_preview = '';

				// Parse article content if specified
				if (isset($articles['article_content']))
				{
					if (!isset($articles['article_content_uid']))
					{
						// Before we are able to display the preview and plane text, we need to parse our request_var()'d value...
						$articles['article_content_uid'] = '';
						$articles['article_content_bitfield'] = '';
						$articles['article_content_options'] = 0;

						generate_text_for_storage($articles['article_content'], $articles['article_content_uid'], $articles['article_content_bitfield'], $articles['article_content_options'], request_var('allow_bbcode', false), request_var('allow_urls', false), request_var('allow_smilies', false));
					}

					// Generate preview content
					$article_content_preview = generate_text_for_display($articles['article_content'], $articles['article_content_uid'], $articles['article_content_bitfield'], $articles['article_content_options']);

					// Decode...
					$article_content_data = generate_text_for_edit($articles['article_content'], $articles['article_content_uid'], $articles['article_content_options']);
				}

				$template->assign_vars(array(
					'ARTICLES_PATH'	=> $phpbb_root_path . $config['express_article_images_path'],

					'ARTICLE_TITLE'				=> (isset($articles['article_title'])) ? $articles['article_title'] : '',
					'ARTICLE_INTRO'				=> (isset($articles['article_intro'])) ? $articles['article_intro'] : '',
					'ARTICLE_IMAGE'				=> ($edit_img) ? $phpbb_root_path . $config['express_article_images_path'] . '/' . $edit_img : $phpbb_admin_path . 'images/spacer.gif',
					'ARTICLE_SIMILAR'			=> (isset($articles['article_similar'])) ? $articles['article_similar'] : '',
					'ARTICLE_SOURCE'			=> (isset($articles['article_source'])) ? $articles['article_source'] : '',
					'ARTICLE_CONTENT'			=> $article_content_data['text'],
					'ARTICLE_CONTENT_PREVIEW'	=> $article_content_preview,

					'U_BACK'	=> $this->u_action,
					'U_ACTION'	=> $this->u_action . '&amp;id=' . $article_id,

					'S_EDIT'					=> true,
					'S_FILENAME_LIST'			=> $img_filename_list,
					'S_CAT_OPTIONS'				=> $s_cat_options,
					'S_CONTENT_BBCODE_CHECKED'	=> ($article_content_data['allow_bbcode']) ? true : false,
					'S_CONTENT_SMILIES_CHECKED'	=> ($article_content_data['allow_smilies']) ? true : false,
					'S_CONTENT_URLS_CHECKED'	=> ($article_content_data['allow_urls']) ? true : false,
				));

				return;

			break;
		}

		// Sorting
		$limit_days = array(0 => $user->lang['ALL_ENTRIES'], 1 => $user->lang['1_DAY'], 7 => $user->lang['7_DAYS'], 14 => $user->lang['2_WEEKS'], 30 => $user->lang['1_MONTH'], 90 => $user->lang['3_MONTHS'], 180 => $user->lang['6_MONTHS'], 365 => $user->lang['1_YEAR']);
		$sort_by_text = array('n' => $user->lang['SORT_ARTICLE_TITLE'], 'v' => $user->lang['SORT_ARTICLE_VIEWS'], 'c' => $user->lang['SORT_ARTICLE_COMMENTS']);
		$sort_by_sql = array('n' => 'article_title', 'v' => 'article_views', 'c' => 'article_comments');

		$s_limit_days = $s_sort_key = $s_sort_dir = $u_sort_param = '';
		gen_sort_selects($limit_days, $sort_by_text, $sort_days, $sort_key, $sort_dir, $s_limit_days, $s_sort_key, $s_sort_dir, $u_sort_param);

		// Define where and sort SQL for use in displaying articles
		$sql_where = ($sort_days) ? (time() - ($sort_days * 86400)) : 0;
		$sql_sort = $sort_by_sql[$sort_key] . ' ' . (($sort_dir == 'd') ? 'DESC' : 'ASC');

		$article_data = array();
		$article_count = 0;

		$start = view_express_articles($cat, $article_data, $article_count, $config['express_articles_per_page'], $start, $sql_where, $sql_sort);

		// Load category jumpbox
		$sql = 'SELECT cat_id, cat_name, cat_articles
			FROM ' . EXPRESS_CATEGORIES_TABLE . '
			ORDER BY cat_order';
		$result = $db->sql_query($sql);

		while ($row = $db->sql_fetchrow($result))
		{
			$template->assign_block_vars('jumpbox', array(
				'CAT_ID'		=> $row['cat_id'],
				'CAT_NAME'		=> $row['cat_name'],
				'CAT_ARTICLES'	=> $row['cat_articles'],
				'SELECTED'		=> ($row['cat_id'] == $cat) ? ' selected="selected"' : '',
			));
		}
		$db->sql_freeresult($result);

		$template->assign_vars(array(
			'CAT_ID'		=> $cat,
			'PAGINATION'	=> generate_pagination($this->u_action . "&amp;$u_sort_param", $article_count, $config['express_articles_per_page'], $start, true),

			'U_ACTION'		=> $this->u_action,

			'S_JUMPBOX_ACTION'	=> append_sid("{$phpbb_admin_path}index.$phpEx", "i=$id&amp;mode=$mode"),
			'S_LIMIT_DAYS'		=> $s_limit_days,
			'S_SORT_KEY'		=> $s_sort_key,
			'S_SORT_DIR'		=> $s_sort_dir,
			'S_ON_PAGE'			=> on_page($article_count, $config['express_articles_per_page'], $start),
		));

		foreach ($article_data as $row)
		{
			// Get category name of each article
			$sql = 'SELECT cat_name
				FROM ' . EXPRESS_CATEGORIES_TABLE . "
				WHERE cat_id = " . $row['article_cat'];
			$result = $db->sql_query($sql);
			$cat_row = $db->sql_fetchrow($result);
			$db->sql_freeresult($result);

			if ($cat_row)
			{
				$template->assign_block_vars('articles', array(
					'ARTICLE_CAT'	=> $cat_row['cat_name'],
					'ARTICLE_TITLE'	=> $row['article_title'],
					'ARTICLE_INTRO'	=> $row['article_intro'],
					'ARTICLE_IMAGE'	=> $phpbb_root_path . $config['express_article_images_path'] . '/' . $row['article_image'],

					'U_EDIT'	=> $this->u_action . '&amp;action=edit&amp;id=' . $row['article_id'],
					'U_DELETE'	=> $this->u_action . '&amp;action=delete&amp;id=' . $row['article_id'],

					'S_ARTICLE_IMAGE'	=> ($row['article_image']) ? true : false,
				));
			}
		}
	}
}

?>